#include "matrixkeys_control.h"

static unsigned int Key_States = 0xFFFF; // 16个按键默认全关闭

void MatrixKeys_Init() {
    Hal_MatrixKeys_Init();
}

/**
 * @brief 判断按键是否处于某种状态
 * @param row 按键行下标
 * @param col 按键列下标
 * @param state 目标状态
 * @return 是返回1，不是返回0
 */ 
char MatrixKeys_IsState(char row, char col, char state) {
    if (state == UP) {
        return ((Key_States >> (row * COL_NUM + col)) & 1);
    }else if (state == DOWN) {
        return !((Key_States >> (row * COL_NUM + col)) & 1);
    }
}

/**
 * @brief 更新按键状态位
 * @param row 按键行下标
 * @param col 按键列下标
 * @param state 目标状态
 */
void MatrixKeys_SetState(char row, char col, char state) {
    if (state == UP) {//置1
        Key_States |= (1<<(row*COL_NUM+col));
    }
    if (state == DOWN) {//置0
        Key_States &= ~(1 << (row * COL_NUM + col));
    }
}


/**
 * @brief 矩阵按键扫描，并调用回调函数
 * @return 返回当前按键状态值
 */
unsigned int MatrixKey_Scan() {
    char i, j; // 行号、列号
    for (i = 0; i < ROW_NUM; i++) {
        Hal_SetRowPower(i);
        for (j = 0; j < COL_NUM; j++) {
            if (Hal_ReadColState(j) == DOWN &&MatrixKeys_IsState(i,j,UP)){
                MatrixKeys_SetState(i,j, DOWN);
                #if KeyPressed_Switch
                Key_Is_Pressed(i, j);//按键按下的回调函数
                #endif
            }
            if(Hal_ReadColState(j) == UP &&MatrixKeys_IsState(i,j,DOWN)){
                MatrixKeys_SetState(i,j, UP);
                #if KeyRaiised_Swtich
                Key_Is_Raised(i, j);//按键抬起的回调函数
                #endif
            }
        }
    }
    return Key_States;
}

void EEPROM_Write(unsigned int EE_address, unsigned char *DataAddress, unsigned int number){
    HAL_WriteEEPROM(EE_address, DataAddress, number);
}

void EEPROM_Read(unsigned int EE_address, unsigned char *DataAddress, unsigned int number){
    HAL_ReadEEPROM(EE_address, DataAddress, number);
}

void EEPROM_Erase(unsigned int EE_address){
    HAL_EEPROMErase(EE_address);
}

